<template>
  <el-card>
    <h2>门店开业设置</h2>
    <div v-if="store">
      <div style="margin-bottom:16px;">
        <b>门店名称：</b>{{ store.storeName }}<br />
        <b>门店ID：</b>{{ store.storeId }}
      </div>
      <div v-if="editMode && employee1Photos">
        <h4>员工1上传图片（可修改）</h4>
        <div style="margin-bottom:8px;">
          <div>
            <b>菜单照：</b>
            <span v-if="!employee1Photos.menuImage" style="color: red;">无图片</span>
            <img v-if="employee1Photos.menuImage" :src="employee1Photos.menuImage" style="max-width:120px;max-height:80px;vertical-align:middle;" />
          </div>
          <div>
            <b>装修照：</b>
            <span v-if="!employee1Photos.decorationImage" style="color: red;">无图片</span>
            <img v-if="employee1Photos.decorationImage" :src="employee1Photos.decorationImage" style="max-width:120px;max-height:80px;vertical-align:middle;" />
          </div>
          <div>
            <b>活动照：</b>
            <span v-if="!employee1Photos.activityImage" style="color: red;">无图片</span>
            <img v-if="employee1Photos.activityImage" :src="employee1Photos.activityImage" style="max-width:120px;max-height:80px;vertical-align:middle;" />
          </div>
          <div>
            <b>配置照：</b>
            <span v-if="!employee1Photos.configImage" style="color: red;">无图片</span>
            <img v-if="employee1Photos.configImage" :src="employee1Photos.configImage" style="max-width:120px;max-height:80px;vertical-align:middle;" />
          </div>
        </div>

        <el-button type="primary" @click="showEditEmployee1 = true">修改员工1图片</el-button>
        <el-dialog v-model="showEditEmployee1" title="修改员工1图片" width="500px">
          <el-form :model="editEmployee1Form" label-width="80px">
            <el-form-item label="菜单照">
              <UploadImage v-model="editEmployee1Form.menuImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
            </el-form-item>
            <el-form-item label="装修照">
              <UploadImage v-model="editEmployee1Form.decorationImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
            </el-form-item>
            <el-form-item label="活动照">
              <UploadImage v-model="editEmployee1Form.activityImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
            </el-form-item>
            <el-form-item label="配置照">
              <UploadImage v-model="editEmployee1Form.configImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showEditEmployee1 = false">取消</el-button>
            <el-button type="primary" @click="submitEditEmployee1">保存</el-button>
          </template>
        </el-dialog>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="开业时间" prop="openingDate">
          <el-date-picker v-model="form.openingDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="培训证明" prop="trainingImageArr">
          <UploadImage v-model="form.trainingImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="onSubmit" 
            :disabled="!canSubmit || submitting"
            :loading="submitting"
          >
            {{ submitting ? '提交中...' : '提交' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else>加载中...</div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import { ElMessage } from 'element-plus';
import UploadImage from '@/components/UploadImage.vue';

const route = useRoute();
const router = useRouter();
const store = ref(null);
const formRef = ref();
const userStore = useUserStore();
const form = ref({
  openingDate: '',
  trainingImageArr: [],
});
const rules = {
  openingDate: [{ required: true, message: '请选择开业时间', trigger: 'blur' }],
  trainingImageArr: [{ required: true, type: 'array', min: 1, message: '请上传培训证明', trigger: 'change' }],
};

const submitting = ref(false);

// 计算是否可以提交
const canSubmit = computed(() => {
  return form.value.openingDate && 
         form.value.trainingImageArr.length > 0 && 
         form.value.trainingImageArr[0]?.url;
});

const editMode = ref(false);
const employee1Photos = ref(null);
const showEditEmployee1 = ref(false);
const editEmployee1Form = ref({
  menuImageArr: [],
  decorationImageArr: [],
  activityImageArr: [],
  configImageArr: [],
});

function isAllImagesUploaded() {
  // 检查培训证明图片是否上传完成
  const trainingImageArr = form.value.trainingImageArr;
  if (
    !trainingImageArr ||
    trainingImageArr.length === 0 ||
    trainingImageArr.some(f => f.status === 'uploading' || f.status === 'ready') || // 还在上传
    !trainingImageArr.some(f => f.url && (f.url.startsWith('http://') || f.url.startsWith('https://')))
  ) {
    return false;
  }
  return true;
}

async function fetchStore() {
  try {
    const res = await fetch(`http://121.43.176.9:8090/api/store/detail/${route.params.storeId}`).then(r => r.json());
    if (res.code === 200) {
      store.value = res.data;
    } else {
      ElMessage.error(res.msg || '获取门店信息失败');
      store.value = null;
    }
  } catch (error) {
    console.error('获取门店信息失败:', error);
    ElMessage.error('获取门店信息失败');
    store.value = null;
  }
}

async function fetchEmployee1Photos() {
  try {
    const res = await fetch(`http://121.43.176.9:8090/api/employee/type1/photos?storeId=${route.params.storeId}`).then(r => r.json());
    if (res.code === 200 && res.data) {
      // 过滤掉 blob URL，只保留有效的图片URL
      const isValidUrl = (url) => {
        return url && !url.startsWith('blob:') && (url.startsWith('http://') || url.startsWith('https://'));
      };
      
      // 先准备过滤后的数据
      const filteredData = {
        ...res.data,
        menuImage: res.data.menuImage && isValidUrl(res.data.menuImage) ? res.data.menuImage : null,
        decorationImage: res.data.decorationImage && isValidUrl(res.data.decorationImage) ? res.data.decorationImage : null,
        activityImage: res.data.activityImage && isValidUrl(res.data.activityImage) ? res.data.activityImage : null,
        configImage: res.data.configImage && isValidUrl(res.data.configImage) ? res.data.configImage : null,
      };
      
      // 直接更新数据
      employee1Photos.value = filteredData;
      
      // 创建新的编辑表单数据
      const newEditFormData = {
        menuImageArr: filteredData.menuImage ? [{ url: filteredData.menuImage }] : [],
        decorationImageArr: filteredData.decorationImage ? [{ url: filteredData.decorationImage }] : [],
        activityImageArr: filteredData.activityImage ? [{ url: filteredData.activityImage }] : [],
        configImageArr: filteredData.configImage ? [{ url: filteredData.configImage }] : [],
      };
      
      // 逐个更新编辑表单字段
      Object.keys(newEditFormData).forEach(key => {
        editEmployee1Form.value[key] = newEditFormData[key];
      });
    } else {
      console.warn('未找到员工1图片数据:', res.msg);
      employee1Photos.value = null;
    }
  } catch (error) {
    console.error('获取员工1图片失败:', error);
    ElMessage.error('获取员工1图片失败');
    employee1Photos.value = null;
  }
}

async function submitEditEmployee1() {
  // 这里假设有后端接口支持员工1图片修改
  const dto = {
    storeId: route.params.storeId,
    menuImage: editEmployee1Form.value.menuImageArr[0]?.url || '',
    decorationImage: editEmployee1Form.value.decorationImageArr[0]?.url || '',
    activityImage: editEmployee1Form.value.activityImageArr[0]?.url || '',
    configImage: editEmployee1Form.value.configImageArr[0]?.url || '',
  };
  const res = await fetch('http://121.43.176.9:8090/api/employee/type1/submit', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(dto),
  }).then(r => r.json());
  if (res.code === 200) {
    ElMessage.success('修改成功');
    showEditEmployee1.value = false;
    fetchEmployee1Photos();
  } else {
    ElMessage.error(res.msg || '修改失败');
  }
}

async function onSubmit() {
  if (submitting.value) {
    ElMessage.warning('正在提交中，请稍候...');
    return;
  }
  
  if (!canSubmit.value) {
    ElMessage.warning('请确保开业时间已选择且培训证明已上传完成');
    return;
  }

  // 新增：图片上传状态校验
  if (!isAllImagesUploaded()) {
    ElMessage.error('请等待培训证明图片上传完成后再提交');
    return;
  }
  
  try {
    await formRef.value.validate();
  } catch (err) {
    const firstError = Object.values(err)[0]?.[0]?.message;
    if (firstError) {
      ElMessage.error(firstError);
    }
    return;
  }
  
  submitting.value = true;
  
  try {
    const dto = {
      employeeId: userStore.userId,
      storeId: route.params.storeId,
      openingDate: form.value.openingDate,
      trainingImage: form.value.trainingImageArr[0]?.url || '',
    };
    const res = await fetch('http://121.43.176.9:8090/api/employee/type2/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(dto),
    }).then(r => r.json());
    if (res.code === 200) {
      ElMessage.success('提交成功');
      router.push('/employee/type2');
    } else {
      ElMessage.error(res.msg || '提交失败');
    }
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message);
  } finally {
    submitting.value = false;
  }
}

onMounted(async () => {
  try {
    // 先获取门店信息
    await fetchStore();
    // 如果是编辑模式，再获取员工1图片
    if (route.query.edit === '1') {
      editMode.value = true;
      await fetchEmployee1Photos();
    }
  } catch (error) {
    console.error('初始化失败:', error);
  }
});
</script> 